/**
 * Created by huangxuehua on 2017/12/1.
 */
//$(".goBack").click(function(){
//    window.history.go(-1)
//});
var toastLoading = new auiToast({});
var mySwiper = undefined;
var xpHome=new Vue({
    el:"#app",
    data:{
        imgBaseUrl:nUrls.imgBaseUrl,
        goodsIndentInfo:{},//商品订单信息
        content:[],//评论内容
        //rank:[],//评论级别
        submitInfo:{},//是否匿名
        updataImgs:[],//图片评论{goodsid:xx,imgPath:yy} {goodsid:xx,imgPath:yy}{goodsid:xx,imgPath:yy}
        cacheImgList:[],//获取缓存图片信息
        rank:[],//分值
        bigImgArr:[],//大图列表
        bigImgIndx:1,//当前显示图片
        isShowSwiper:false, //是否显示大图
    },
    methods:{
        getImage:function(url){//加载图片  处理 url为空 加载出错
            if(url){
                return xpHome.imgBaseUrl+url;
            }
        },
        initData:function(){
            var IndentInfo = window.localStorage.getItem("commentGoodsInfo"); //接收订单页面数据
            if (IndentInfo) {
                xpHome.goodsIndentInfo = JSON.parse(IndentInfo);
                console.log(JSON.parse(IndentInfo))
                setTimeout(function(){ ////评价级别星星
                    for(var v=0;v<xpHome.goodsIndentInfo.children.length;v++){
                        Vue.set(xpHome.rank, v, 5);//默认5分
                    }
                },10);
            }
        },
        clickXingXing:function(index,param) {  //点击星星获得级别
            Vue.set(xpHome.rank, index, param);//记录当前打分
           //console.log("-xpHome.rank--",xpHome.rank[index]);
           out(index,param);//设置星星数
         },
        addComment:function(){//添加评论
            var data = {
                "userid":userInfo.userid,//客户id
                access_token:userInfo.access_token
            };
            var isInput = 0 ; //0个填写
            for(var v=0;v<xpHome.goodsIndentInfo.children.length;v++){
                var temp  = xpHome.goodsIndentInfo.children[v];
                //非空判断
                if(xpHome.content[v]){ //其中一个填写评论 就可以提交
                    isInput +=1;
                }
                data["data["+v+"][content]"] = xpHome.content[v]; //评论
                data["data["+v+"][comment_rank]"] = xpHome.rank[v];//星级
                data["data["+v+"][is_niming]"] = xpHome.submitInfo[v]==true?1:0;//是否匿名
                data["data["+v+"][goods_id]"] = temp.goods_id;//商品id
                data["data["+v+"][rec_id]"] = temp.rec_id;//商品id
            }
            if(isInput == 0){
                var toast = new auiToast(); //初始化toast事件
                toast.custom({
                    title: "请填写评论",
                    html: '',
                    duration: 2000
                })
                return;
            }
            if(xpHome.goodsIndentInfo.children.length == 1){
                xpHome.submitCommit(data);
            }else{
                var commentNum=xpHome.goodsIndentInfo.children.length - isInput;
                //console.log("======commentNum==", commentNum);
                if(commentNum==0){ //全部已经评论，直接提交
                    xpHome.submitCommit(data);
                }else{
                    var dialog = new auiDialog();
                    dialog.alert({
                        title:"提示",
                        msg:"还有"+commentNum+"个商品未评论<br>是否提交？",
                        buttons:['取消','确定']
                    },function(ret) {
                        if (ret.buttonIndex == 2) {//确定
                            xpHome.submitCommit(data);
                        }
                    })
                }

            }
        },
        submitCommit:function(data){//提交评论
            //信息提交
            $.ajax({
                url: nUrls.addComment,
                type: "POST",
                data: data,
                success: function (dd) {
                    //console.log("=commentList=", data);
                    var result = eval('(' + dd + ')');//JOSN 数据转 JOSN对象
                    if (result && result.code === 200) {
                        var toast = new auiToast(); //初始化toast事件
                        toast.custom({
                            title: "评论成功",
                            html: '',
                            duration: 2000
                        })
                        window.location.href = "./comment_succeed.html"
                    }
                },
                error: function () {
                    console.log("添加评论失败")
                }
            })
        },
        checkedBtn:function(index){
            //Vue.set(xpHome.submitInfo,index,!xpHome.submitInfo[index]);
            xpHome.submitInfo=!xpHome.submitInfo;
        },
        getImageLength:function(goodsid){
            var lgh = 0;
            var vv = xpHome.updataImgs;
            for(var i=0;i<vv.length;i++){
                var temp = vv[i];
                if(temp.goodsid == goodsid){
                    lgh++;
                }
            }
          return lgh;
        },
        addImage:function(e,it,recid,goodsid){    //添加图片
            var vv = $("#input_file"+goodsid).val();
            if(!vv){
                return ;
            }
            toastLoading.loading({
                title:"加载中",
            },function(ret){
            });
            var reader = new FileReader();
            reader.onload = (function (file) {
                return function (e) {
                    var str = this.result;
                    compressImgByExactWidth(this.result,function(data){
                        //xpHome.updataImgs.push(data);//应该不要的
                        //data = data.replace("data:image/png;base64,","");
                        //data = encodeURIComponent(data);
                        requestData(nUrls.uploadUrl,function(d){
                            console.log("+++++++",d);
                            if(d && d.code == 200){
                                //服务器返回的是图片路径
                                var temp = {
                                    "goodsid":goodsid,
                                    "imgPath":nUrls.imgNativeUrl+d.data,//绝对路径  全路径
                                    "relativePath":d.data, //相对路径
                                    "recid":recid,
                                    "comment_images_id":d.comment_images_id
                                };
                                xpHome.updataImgs.push(temp); //页面根据路径显示
                                toastLoading.hide();
                            }
                        },null,{imgStr:data,recid:recid,access_token:userInfo.access_token,goodsid:goodsid})
                    });
                };
            })(e.target.files[0]);
            reader.readAsDataURL(e.target.files[0]);
        },

        delImage:function(num,index){          //删除照片
            var temp = xpHome.updataImgs[num];
            var rec=xpHome.goodsIndentInfo.children[index];
            var data={
                "data[comment_images_id]" :temp.comment_images_id,//商品id
                "data[imgPath]": temp.relativePath ,//图片路径
                "data[order_goods_id]":rec.rec_id,
                "access_token":userInfo.access_token,
            }
            //console.log("++delImage+++",data);
            $.ajax({
                url:nUrls.getDelCommentImgUrl,
                type:"Post",
                data:data,
                success:function(data){
                    //console.log("----data[imgPath]-----",data)
                    var result=eval('('+data+')') ;//JOSN 数据转 JOSN对象
                    if(result && result.code===200){
                        xpHome.updataImgs.splice(num,1); //删除页面图片
                    }
                },
                error:function(){
                    console.log("删除图片出错")
                }
            })
        },
        getCacheImgInfo:function(){ // 获取评价上传缓存图片
            var rec = xpHome.goodsIndentInfo.children;
            if(rec && rec.length>0){
                var data={
                    "data[order_id]":rec[0].order_id,
                }
                $.ajax({
                    url:nUrls.getCacheImgUrl,
                    type:"Post",
                    data:data,
                    success:function(data){
                        var result=eval('('+data+')') ;//JOSN 数据转 JOSN对象
                        if(result && result.code===200){ // 返回缺少 goods_id
                            xpHome.cacheImgList=result.data;
                            // updataImgs:[],//图片评论{goodsid:xx,imgPath:yy} {goodsid:xx,imgPath:yy}{goodsid:xx,imgPath:yy}
                            console.log("--xpHome.cacheImgList-",xpHome.cacheImgList);
                            xpHome.getBeforeImages();//图片处理
                        }
                    },
                    error:function(){
                        console.log("获取缓存图片出错")
                    }
                })
            }



        },
        getBeforeImages:function(){//获取之前上传的图片
            var rec = xpHome.goodsIndentInfo.children;
            for(var i=0;i<rec.length;i++){
                var name = rec[i].rec_id;
                var goods_id = rec[i].goods_id;
                //console.log("- rec i--",name);
                if(xpHome.cacheImgList){
                    var temp1 = xpHome.cacheImgList;
                    var vImgs = temp1[name];//原来已经上传的图片数组
                    if(vImgs){
                        for(var v=0;v<vImgs.length;v++){
                            var temp = {
                                "goodsid":goods_id,
                                "imgPath":nUrls.imgNativeUrl+vImgs[v].comment_image,//绝对路径  全路径
                                "relativePath":vImgs[v].comment_image, //相对路径
                                "recid":name,
                                "comment_images_id":vImgs[v].comment_images_id
                            };
                            xpHome.updataImgs.push(temp);
                        }
                    }
                }
            }
        },
        showClick:function(index){
            xpHome.bigImgIndx = index + 1; //当前显示
            xpHome.showSwiper(index);
            //xpHome.bigImgShowSrc = $(this).attr("src");
        },
        showSwiper: function(idx) {    //图片滑动
            xpHome.isShowSwiper = true;
            document.documentElement.scrollTop = 0;
            document.body.scrollTop = 0;
            touchMoveCant("#mySwiper");
            $("#commentBody").css("overflow","hidden");
            this.$nextTick(function() {
                if(mySwiper) {
                    mySwiper.destroy();
                    mySwiper = undefined;
                }
                mySwiper = new Swiper("#mySwiper", {
                    direction: 'horizontal',
                    loop: false,
                    zoom: true,
                    onSlideChangeEnd: function(swiper) { //水平滑动切换 
                        xpHome.bigImgIndx = swiper.activeIndex + 1; //滚动显示
                    }
                });
                if(idx === 0) {
                    mySwiper.slideTo(1, 0);
                    mySwiper.slideTo(0, 0);
                } else {
                    mySwiper.slideTo(idx, 0);
                }
            });
        },
        closeSwiper: function() {  //关闭滑动、大图
            $("#commentBody").css("overflow","auto");
            xpHome.isShowSwiper = false;
        },
        goOnLine:function(){  //断网刷新
            nUtils.onLine();
        }
    }
})

function compressImgByExactWidth(imgData,callback,width){
    if(!imgData)return;
    callback = callback || function(){};
    width = width || 320;//默认宽度320
    var canvas = document.createElement('canvas');
    var img = new Image();
    img.onload = function(){
        if(img.width > width) {//按最大高度等比缩放
            img.height *= width / img.width;
            img.width = width;
            //console.log("width",img.width)
        }
        var ctx = canvas.getContext("2d");
        ctx.clearRect(0, 0, canvas.width, canvas.height); // canvas清屏
        canvas.width = img.width;
        canvas.height = img.height;//重置canvans宽高
        ctx.drawImage(img, 0, 0, img.width, img.height); // 将图像绘制到canvas上
        callback(canvas.toDataURL("image/png"));
    };
    img.src = imgData;
}
//请求数据
function requestData(url,callback,getParams,postParams){
    if(!url){
        return;
    }
    var firstParam = true;
    if(getParams){
        if(url.indexOf('?')>-1){
            //说明之前已经拼接了参数
            firstParam = false;
        }
        for(var p in getParams){
            url +=firstParam?'?':'&';
            firstParam  = false;
            url += p + '=' + getParams[p];
        }
    }
    if(window.XMLHttpRequest) { // IE7+, Firefox, Chrome, Opera, Safari 代码
        xmlhttp = new XMLHttpRequest();
    } else { // IE6, IE5 代码
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function(){
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            if(callback){
                //可能有安全隐患！！！！！！
                var data = eval('(' + xmlhttp.responseText + ')');
                callback(data);
            }
        }
    };
    xmlhttp.open("POST", url, true);
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    if(postParams) {
        firstParam = true;
        var postData = "";
        for(var p in postParams){
            if(!firstParam){
                postData+="&";
            }
            firstParam = false;
            postData += p+"="+postParams[p];
        }
    }
    xmlhttp.send(postData);
}

$(function(){
    xpHome.initData();
    xpHome.getCacheImgInfo();//获取上传图片的缓存
})
$('textarea').keyup(function () {
    $(this).height(this.scrollHeight);
});
function touchMoveCant(ele){//ios 等其他型号手机 滑动问题
    document.querySelector(ele).addEventListener("touchmove", function(e){
        e.preventDefault();
    });
}

//var check = 0;//该变量是记录当前选择的评分

/*out 方法是鼠标移除事件的处理方法，当鼠标移出时，恢复到我的打分情况*/
function out(index,check){
    $("#star"+index+"1").attr("src","../../icon/4-1/redXIng.png");
    $("#star"+index+"2").attr("src","../../icon/4-1/redXIng.png");
    $("#star"+index+"3").attr("src","../../icon/4-1/redXIng.png");
    $("#star"+index+"4").attr("src","../../icon/4-1/redXIng.png");
    $("#star"+index+"5").attr("src","../../icon/4-1/redXIng.png");
    for(var v=1;v<=check;v++){//打分是1，设置第一颗星星亮，其他星星暗，其他情况以此类推
        $("#star"+index+v).attr("src","../../icon/4-1/xingxing.png");
    }
}


